package com.my.security.service.impl;

import com.my.security.dao.PermissionMapper;
import com.my.security.dao.UserMapper;
import com.my.security.model.AuthenticationRequest;
import com.my.security.model.Permission;
import com.my.security.model.User;
import com.my.security.service.AuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lbb
 * @fileName AuthenticationServiceImpl
 * @description
 * @date 2020/5/12 12:37
 */
@Service
public class AuthenticationServiceImpl implements AuthenticationService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public User authentication(AuthenticationRequest authenticationRequest) {
        if(authenticationRequest==null||authenticationRequest.getUsername()==null||authenticationRequest.getPassword()==null){
            throw new RuntimeException("账号或密码不能为空");
        }
        User user=userMapper.getUserByName(authenticationRequest.getUsername());
        if(user==null){
            throw new RuntimeException("账号有误");
        }
        if(!user.getPassword().equals(authenticationRequest.getPassword())){
            throw new RuntimeException("密码有误");
        }
        //获取用户权限列表
        List<Permission> list=permissionMapper.getUserPermission(user.getUsername());
        Set<String> authorities=new HashSet<String>();
        list.stream().forEach(e->authorities.add(e.getPermissionTag()));
        user.setAuthorities(authorities);
        return user;
    }
}
